<script setup lang="ts">
import { RouterLink } from 'vue-router'
import { icons, type IconsType } from './menu-icons'

const router = useRouter()

const { collection } = useMenu()

// 根据路由名称查找菜单项及其路径
const findMenuItemPath = (data: MenuModel[], routerName: string): MenuModel[] | null => {
  const path: MenuModel[] = []

  const find = (items: MenuModel[], target: string): boolean => {
    for (const item of items) {
      path.push(item)
      if (item.router_name === target) {
        return true
      }
      if (item.children) {
        if (find(item.children, target)) {
          return true
        }
      }
      path.pop()
    }
    return false
  }

  return find(data, routerName) ? path : null
}

// 生成面包屑数据
const breadcrumbItems = computed(() => {
  const currentRoute = router.currentRoute.value
  const menuData = collection.value?.data || []
  const menuPath = findMenuItemPath(menuData, currentRoute.name as string)

  if (!menuPath) return []

  return menuPath.map((item) => ({
    title: item.label,
    icon: item.icon,
    path: item.children ? undefined : { name: item.router_name },
    children: item.children,
  }))
})
</script>

<template>
  <section class="flex items-center font-bold pl-3 text-2xl">
    <n-breadcrumb>
      <n-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index">
        <template v-if="item.path">
          <router-link :to="item.path" class="flex items-center">
            <component :is="icons[item.icon as IconsType]" class="mr-1" />
            {{ item.title }}
          </router-link>
        </template>
        <template v-else>
          <n-dropdown
            trigger="click"
            :options="
              item.children
                ?.filter((child) => child.router_name !== router.currentRoute.value.name)
                .map((child) => ({
                  label: () =>
                    h(
                      RouterLink,
                      {
                        to: { name: child.router_name },
                        class: 'flex items-center',
                      },
                      () => [
                        h(icons[child.icon as keyof typeof icons], {
                          class: 'mr-1',
                        }),
                        child.label,
                      ],
                    ),
                }))
            "
          >
            <div class="flex items-center cursor-pointer">
              <component :is="icons[item.icon as keyof typeof icons]" class="mr-1" />
              {{ item.title }}
            </div>
          </n-dropdown>
        </template>
      </n-breadcrumb-item>
    </n-breadcrumb>
  </section>
</template>
